package com.example.controller;

import com.gitee.loyo.utils.OkHttpHelper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;

@Controller
@RequestMapping("/extra/bp/evcs/v1/")
public class ProxyController {
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/**")
    ResponseEntity<String> proxy(RequestEntity requestEntity) throws URISyntaxException {
        URI current = requestEntity.getUrl();
        URI remoteService = URI.create("http://8.129.168.224:9999");
        URI uri = new URI(
            current.getScheme(),
            current.getUserInfo(),
            remoteService.getHost(),
            remoteService.getPort(),
            current.getPath(),
            current.getQuery(),
            current.getFragment()
        );
        RequestEntity forward = new RequestEntity(
            requestEntity.getBody(),
            requestEntity.getHeaders(),
            requestEntity.getMethod(),
            uri
        );
        try{
            return restTemplate.exchange(forward, String.class);
        }catch (HttpStatusCodeException e){
            return new ResponseEntity(e.getResponseBodyAsString(), e.getResponseHeaders(), e.getStatusCode());
        }
    }
}
